import random

from django.http import HttpResponse
from django.shortcuts import render
from rest_framework import status
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.generics import GenericAPIView
from meiduo.utils.yuntongxun.sms import CCP
from meiduo.libs.captcha.captcha import captcha
from django_redis import get_redis_connection
import logging
from celery_tasks.sms import tasks


logger = logging.getLogger('django')
# Create your views here.
# url('^image_codes/(?P<image_code_id>[\w-]+)/$', views.ImageCodeView.as_view()),
from verifications import constants
# from verifications import serializers
from verifications.serializers import ImageCodeCheckSerializer
from django_redis import get_redis_connection

class ImageCodeView(APIView):
    def get(self, request, image_code_id):
        """获取图片验证码id 并且返回图片"""
        # generate_captcha返回两个参数 第一个参数图片验证码文本，第二个是图片内容(二进制)
        print("someone call me")
        text, image = captcha.generate_captcha()
        # 保存真实值
        redis_conn = get_redis_connection('verify_codes')
        redis_conn.setex("img_%s" % image_code_id, constants.IMAGE_CODE_REDIS_EXPIRES, text)
        # print(text)
        return HttpResponse(image, content_type='image/jpg')


# url('^sms_codes/(?P<mobile>1[3-9]\d{9})/$', views.SMSCodeView.as_view()),


class SMSCodeView(GenericAPIView):
    """
    短信验证
    传入参数 mobile  image_code_id  text
    """
    serializer_class = ImageCodeCheckSerializer
    def get(self,request, mobile):
        """
        # 使用序列化器进行图形验证码验证
        给手机号发送短信
        将短信内容保存在redis中　以便后面验证
        :return:
        """
        # print('*'*50, 1)
        seriallizer = self.get_serializer(data = request.query_params)
        seriallizer.is_valid(raise_exception=True)
        # 生成短信验证码
        # print('*' * 50, 2)
        sms_code = random.randint(100000, 1000000)
        # 将短信信息保存到redis中
        # 在保存到redis中进行检验　如果在一分钟之内　已经发送ｕｏ就不再发送

        redis_conn = get_redis_connection("verify_codes")

        redis_conn.setex('sms_%s'%mobile, constants.MOBILE_REDIS_EXPIRES, sms_code)
        # 设立标记
        redis_conn.setex('send_flag_%s'%mobile, constants.VERIFI_MOBILE_CODE_INTERVAL, 1)

        # 发送短信
        # try:
        #     ccp = CCP()
        #     result = ccp.send_template_sms(mobile, [sms_code, constants.MOBILE_REDIS_EXPIRES], constants.SMS_TEM_ID)
        # except Exception as e:
        #     logger.error('发送短信异常, mobile:%s' %mobile)
        #     return Response({'message':'filed'}, status=status.HTTP_503_SERVICE_UNAVAILABLE)
        # else:
        #     if result == 0:
        #         logger.info('发送短信成功 mobile:%s 验证码: %s' %(mobile, sms_code))
        #         return Response({"message":"OK"})
        #     else:
        #         logger.info('发送短信失败 mobile:%s'%mobile)
        #         return Response({"message":"failed"})
        tasks.send_msg.delay(mobile, sms_code, constants.MOBILE_REDIS_EXPIRES//60)
        return Response({"message":"OK"})